﻿/// <Reference Name="MicrosoftAjax.js" />
/// <Reference Path="../jQuery/jquery.js" />



(function () {

    var scriptName = 'SharePointDataLists';


    function execute() {

        Type.registerNamespace('Sys.SharePoint');
        

        Sys.SharePoint.Lists = function () {
            /// <summary>Sys.SharePoint.Lists static class</summary>
            throw 'Cannot initialize Sys.SharePoint.Lists static class';
        }


        Sys.SharePoint.Lists.AddItem = function (listName, listItem, web, success, fail) {
            /// <signature>
            ///     <summary>Add item to the list</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItem" type="Object" mayBeNull="false" optional="false">List item</param>
            ///     <param type="SP.Web" mayBeNull="false" optional="true">Web</param>
            /// </signature>
            ///  <signature>
            ///     <summary>Add item to the list</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItem" type="Object" mayBeNull="false" optional="false">List item</param>
            ///     <param type="SP.Web" mayBeNull="true" optional="false">Web</param>
            ///     <param name="success" type="Function" mayBeNull="false" optional="false">Success</param>
            ///     <param name="fail" type="Function" mayBeNull="false" optional="true">Fail</param>
            ///  </signature>

            var e1 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItem', type: Object, mayBeNull: false, optional: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: false, optional: true }], true);
            var e2 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItem', type: Object, mayBeNull: false, optional: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: true, optional: false },
                                                             { name: 'success', type: Function, mayBeNull: false, optional: false },
                                                             { name: 'fail', type: Function, mayBeNull: false, optional: true }], true);
            if (e1 !== null && e2 !== null)
                throw 'Invalid parameters calling AddItem';

            var isDeffered = (e1 === null && e2 !== null) ? true : false;
            var ctx = (typeof web === 'undefined' || web === null) ? SP.ClientContext.get_current() : web.get_context();
            var web = (typeof web === 'undefined' || web === null) ? ctx.get_web() : web;
            var _listItems = [listItem];
            var deffered;


            if (isDeffered === true) {
                var _addItem = Sys.SharePoint.Lists._defferedAddItems(listName, _listItems, ctx, web);
                deffered = _addItem.then(function (items) {
                    return items[0];
                }, function (error) {
                    return error;
                });
                return deffered;
            }

            var _fail = fail || function (err) { alert(err); }
            var _success = function (results) {
                success(results[0]);
            }
            Sys.SharePoint.Lists._nonDefferedAddItems(listName, _listItems, ctx, web, _success, _fail);

            return null;
        }


        Sys.SharePoint.Lists.AddItems = function (listName, listItems, web, success, fail) {
            /// <signature>
            ///     <summary>Add items to the list</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            ///     <param type="SP.Web" mayBeNull="false" optional="true">Web</param>
            /// </signature>
            /// <signature>
            ///     <summary>Add items to the list</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            ///     <param name="web" type="SP.Web" mayBeNull="true" optional="false">Web</param>
            ///     <param name="success" type="Function" mayBeNull="false" optional="false">Success</param>
            ///     <param name="fail" type="Function" mayBeNull="false" optional="true">Fail</param>
            /// </signature>
            var e1 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItems', type: Array, mayBeNull: false, optional: false, elementType: Object, elementMayBeNull: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: false, optional: true }], true);
            var e2 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItems', type: Array, mayBeNull: false, optional: false, elementType: Object, elementMayBeNull: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: true, optional: false },
                                                             { name: 'success', type: Function, mayBeNull: false, optional: false },
                                                             { name: 'fail', type: Function, mayBeNull: false, optional: true }], true);
            if (e1 !== null && e2 !== null)
                throw 'Invalid parameters calling AddItems';

            // Define context and web objects for operations
            var ctx = (typeof web === 'undefined' || web === null) ? SP.ClientContext.get_current() : web.get_context();
            var web = (typeof web === 'undefined' || web === null) ? ctx.get_web() : web;

            // Use jQuery deffered for operation
            if (e1 === null && e2 !== null) {
                return Sys.SharePoint.Lists._defferedAddItems(listName, listItems, ctx, web);
            }

            // Choose success and fail methods to be executed when operation is ready
            if (e1 !== null && e2 === null) {
                var fail = fail || function (err) { alert(err); };
                Sys.SharePoint.Lists._nonDefferedAddItems(listName, listItems, ctx, web, success, fail);
            }

            return null;
        }


        Sys.SharePoint.Lists._defferedAddItems = function (listName, listItems, ctx, web) {
            /// <summary>Add items to the list using jQuery deffered (internal use)</summary>
            /// <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            /// <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            /// <param name="ctx" type="SP.ClientContext" mayBeNull="false" optional="false">Context</param>
            /// <param name="web" type="SP.Web" mayBeNull="false" optional="false">Web</param>

            var oList = web.get_lists().getByTitle(listName);
            var deffered = jQuery.Deferred();
            var results = [];


            // for each item of in list items we create item in SharePoint list
            for (var i = 0; i < listItems.length; i++) {

                var listItem = listItems[i];
                var listItemCreationInfo = new SP.ListItemCreationInformation();
                var oListItem = oList.addItem(listItemCreationInfo);

                // for each property of current item, we assign field values
                for (var field in listItem) {
                    oListItem.set_item(field, listItem[field]);
                }

                // update and load SharePoint list item and add it to results array
                oListItem.update();
                ctx.load(oListItem);
                results.push(oListItem);
            }


            // context will execute query async
            ctx.executeQueryAsync(function () {
                deffered.resolve(results);
            }, function (sender, args) {
                deffered.reject(args.get_message());
            });

            return deffered.promise();
        }

        Sys.SharePoint.Lists._nonDefferedAddItems = function (listName, listItems, ctx, web, success, fail) {
            /// <summary>Add items to the list (internal use)</summary>
            /// <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            /// <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            /// <param name="ctx" type="SP.ClientContext" mayBeNull="false" optional="true">Context</param>
            /// <param name="web" type="SP.Web" mayBeNull="false" optional="false">Web</param>
            /// <param name="success" type="Function" mayBeNull="false" optional="false">Success</param>   
            /// <param name="fail" type="Function" mayBeNull="false" optional="false">Fail</param>   

            var oList = web.get_lists().getByTitle(listName);
            var results = [];


            // for each item of in list items we create item in SharePoint list
            for (var i = 0; i < listItems.length; i++) {

                var listItem = listItems[i];
                var listItemCreationInfo = new SP.ListItemCreationInformation();
                var oListItem = oList.addItem(listItemCreationInfo);

                // for each property of current item, we assign field values
                for (var field in listItem) {
                    oListItem.set_item(field, listItem[field]);
                }

                // update and load SharePoint list item and add it to results array
                oListItem.update();
                ctx.load(oListItem);
                results.push(oListItem);
            }

            // context will execute query async
            ctx.executeQueryAsync(function () {
                success(results);
            }, function (sender, args) {
                fail(args.get_message());
            });
        }


        Sys.SharePoint.Lists.UpdateItems = function (listName, listItems, web, success, fail) {
            /// <signature>
            ///     <summary>Update list items</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            ///     <param name="web" type="SP.Web" optional="true" mayBeNull="true">Web</param>
            /// </signature>
            /// <signature>
            ///     <summary>Update list items</summary>
            ///     <param name="listName" type="String" mayBeNull="false" optional="false">List name</param>
            ///     <param name="listItems" type="Array" mayBeNull="false" optional="false" elementType="Object" elementMayBeNull="false">List items</param>
            ///     <param name="web" type="SP.Web" optional="false" mayBeNull="true">Web</param>
            ///     <param name="success" type="Function" optional="false" mayBeNull="false">Web</param>
            ///     <param name="fail" type="Function" optional="true" mayBeNull="false">Web</param>
            /// </signature>

            var e1 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItems', type: Array, mayBeNull: false, optional: false, elmentType: Object, elementMayBeNull: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: true, optional: true }], true);

            var e2 = Function.validateParameters(arguments, [{ name: 'listName', type: String, mayBeNull: false, optional: false },
                                                             { name: 'listItems', type: Array, mayBeNull: false, optional: false, elmentType: Object, elementMayBeNull: false },
                                                             { name: 'web', type: SP.Web, mayBeNull: true, optional: false },
                                                             { name: 'success', type: Function, mayBeNull: false, optional: false },
                                                             { name: 'fail', type: Function, mayBeNull: false, optional: true }], true);
            if (e1 !== null && e2 !== null)
                throw 'Invalid parameters specified calling Sys.SharePoint.Lists.UpdateItems';

            // Define context and web objects for operations
            var ctx = (typeof web === 'undefined' || web === null) ? SP.ClientContext.get_current() : web.get_context();
            var web = (typeof web === 'undefined' || web === null) ? ctx.get_web() : web;

            // Operation is using jQuery.Deffered
            if (e1 === null) {
                return Sys.SharePoint.Lists._defferedUpdateItems(listName, listItems, ctx, web);
            }

            // Operation is using callbacks and return null
            if (e2 === null) {
                return null;
            }

            
            return null;
        }


        Sys.SharePoint.Lists._defferedUpdateItems = function (listName, listItems, ctx, web) {

        }

        Sys.SharePoint.Lists._nonDefferedUpdateItems = function (listName, listItems, ctx, web, success, fail) {
        }


        Sys.SharePoint.Lists.registerClass('Sys.SharePoint.Lists');

    }

    

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript(scriptName, ['jQuery'], execute);
    }
    else {
        execute();
    }


})();